package pcbeonjms;

import javax.jms.*;

public class Producator extends Thread {

    private TopicSession m_session;
    private int nr_resurse;
    private long frecventa;
    private int cantitate_generata;
    private Resursa tipResursa;
    private TopicPublisher m_publisher;
    private TopicConnection m_topicConn;

    public Producator(ConnectionFactory m_connFactory, Topic m_topic, Resursa tip, long frecventa, int cantitate) throws JMSException {

        tipResursa = tip;
        nr_resurse = 0;
        this.frecventa = frecventa;
        cantitate_generata = cantitate;
        cantitate_generata = cantitate;
        m_topicConn = ((TopicConnectionFactory) m_connFactory).createTopicConnection();
        m_session = m_topicConn.createTopicSession(false,
                Session.AUTO_ACKNOWLEDGE);
        m_publisher = m_session.createPublisher(m_topic);
        m_publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    }

    public Resursa getTip() {
        return tipResursa;
    }

    private void creeaza_resurse() {
        nr_resurse += cantitate_generata;
    }

    @Override
    public void run() {
        try {
            while (true) {
                creeaza_resurse();
                da_resurse();
                synchronized (this) {
                    wait(frecventa);
                }
            }
        } catch (Exception ex) {
            System.out.println("End producator");
        } finally {
            try {
                m_publisher.close();
            } catch (JMSException ex) {
            }
            try {
                m_session.close();
            } catch (JMSException ex) {
            }
            try {
                m_topicConn.close();
            } catch (JMSException ex) {
            }
        }
    }

    private void da_resurse() throws JMSException {
        TextMessage msg = m_session.createTextMessage();
        msg.setText(tipResursa + "," + nr_resurse);
        nr_resurse = 0;
        m_publisher.publish(msg);
    }
}
